import os
import re
import sys
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime

def parse_txt_file(input_file):
    with open(input_file, 'r') as file:
        lines = file.readlines()
    
    # 初始化数据结构
    timestamps = []
    mem_total = []
    mem_used = []
    mem_free = []
    cpu_total = []
    process_data = {}
    
    # 解析文件内容
    for line in lines:
        if line.startswith('Timestamp'):
            timestamp = line.split(': ')[1].strip()
            timestamps.append(timestamp)
        elif line.startswith('MEM[Total'):
            mem_info = re.findall(r"[\d\.\d]+", line)
            mem_total.append(float(mem_info[0]))
            mem_used.append(float(mem_info[1]))
            mem_free.append(float(mem_info[2]))
        elif line.startswith('CPU[Total'):
            cpu_info = re.findall(r"[\d\.\d]+", line)
            cpu_total.append(float(cpu_info[0]))
        else:
            match = re.match(r"(.+)\[Pid, cpu, mem\]: (\d+), ([\d\.]+) %, ([\d\.]+) MB", line)
            if match:
                process_name = match.group(1).strip()
                pid = int(match.group(2))
                cpu = float(match.group(3))
                mem = float(match.group(4))
                if process_name not in process_data:
                    process_data[process_name] = {'cpu': [], 'mem': []}
                process_data[process_name]['cpu'].append(cpu)
                process_data[process_name]['mem'].append(mem)
    
    return timestamps, mem_total, mem_used, mem_free, cpu_total, process_data

def generate_plots(timestamps, mem_total, mem_used, mem_free, cpu_total, output_dir):
    timestamps_dt = [datetime.strptime(ts, '%Y-%m-%d %H:%M:%S') for ts in timestamps]

    # 创建 CPU 图表
    fig_cpu = go.Figure()
    fig_cpu.add_trace(go.Scatter(x=timestamps_dt, y=cpu_total, mode='lines+markers', marker=dict(size=3), line=dict(width=1), name='Total CPU Usage (%)'))
    fig_cpu.update_layout(title='CPU Usage Over Time',
                          xaxis_title='Timestamp',
                          yaxis_title='CPU Usage (%)',
                          xaxis_tickformat='%Y-%m-%d %H:%M:%S')

    # 创建 MEM 图表
    fig_mem = go.Figure()
    fig_mem.add_trace(go.Scatter(x=timestamps_dt, y=mem_total, mode='lines+markers', marker=dict(size=3), line=dict(width=1), name='Total MEM (MB)'))
    fig_mem.add_trace(go.Scatter(x=timestamps_dt, y=mem_used, mode='lines+markers', marker=dict(size=3), line=dict(width=1), name='Used MEM (MB)'))
    fig_mem.add_trace(go.Scatter(x=timestamps_dt, y=mem_free, mode='lines+markers', marker=dict(size=3), line=dict(width=1), name='Free MEM (MB)'))
    fig_mem.update_layout(title='Memory Usage Over Time',
                          xaxis_title='Timestamp',
                          yaxis_title='Memory (MB)',
                          xaxis_tickformat='%Y-%m-%d %H:%M:%S')

    # 保存图表为HTML文件
    fig_cpu.write_html(os.path.join(output_dir, 'cpu_usage_plot.html'))
    fig_mem.write_html(os.path.join(output_dir, 'mem_usage_plot.html'))

def generate_html(output_file, process_data):
    output_dir = os.path.dirname(output_file)
    
    # 生成HTML文件
    with open(output_file, 'w') as f:
        f.write('<html><head><title>System and Process Monitoring</title></head><body>')
        f.write('<div style="text-align:right; padding: 10px;">')
        f.write('<p>让中国智能车跑在全世界的马路上</p>')
        f.write('<p>数据来源：大卓应用交付部</p>')
        f.write('<p style="color:lightgray;">有任何使用问题请联系 应用交付部-袁宪彬</p>')
        f.write('</div>')
        
        f.write('<h1>System Monitoring</h1>')
        f.write('<iframe src="cpu_usage_plot.html" width="100%" height="500"></iframe>')
        f.write('<iframe src="mem_usage_plot.html" width="100%" height="500"></iframe>')
        
        f.write('<h1>Process Monitoring</h1>')
        f.write('<table border="1">')
        f.write('<tr><th>Process Name</th><th>Min CPU (%)</th><th>Max CPU (%)</th><th>Min MEM (MB)</th><th>Max MEM (MB)</th></tr>')
        
        for process, metrics in process_data.items():
            min_cpu = min(metrics['cpu'])
            max_cpu = max(metrics['cpu'])
            min_mem = min(metrics['mem'])
            max_mem = max(metrics['mem'])
            f.write(f'<tr><td>{process}</td><td>{min_cpu}</td><td>{max_cpu}</td><td>{min_mem}</td><td>{max_mem}</td></tr>')
        
        f.write('</table>')
        f.write('</body></html>')

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python script.py <input_file> <output_file>")
        sys.exit(1)

    input_file = sys.argv[1]
    output_file = sys.argv[2]
    output_dir = os.path.dirname(output_file)

    timestamps, mem_total, mem_used, mem_free, cpu_total, process_data = parse_txt_file(input_file)
    generate_plots(timestamps, mem_total, mem_used, mem_free, cpu_total, output_dir)
    generate_html(output_file, process_data)

